package com.dy.system.service.impl;

import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.system.domain.Menu;
import com.dy.system.mapper.MenuMapper;
import com.dy.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dayong
 * @since 2023-03-09
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper mapper;

    /**
     * 查询上级部门
     * @return
     */
    @Override
    public List<Menu> find() {
        List<Menu> menus = mapper.findAll().stream().filter(Menu -> Objects.nonNull(Menu) && null == Menu.getParentId()).collect(Collectors.toList());
        return menus;
    }

    /**
     * 无限极树
     * @return
     */
    @Override
    public List<Menu> findAllTree() {
        List<Menu> all = mapper.findAll();
        Map<Long, Menu> collect = all.stream().collect(Collectors.toMap(Menu::getId, Menu -> Menu));
        List<Menu> objects = new ArrayList<>();
        for (Menu m: all ) {
            if (null == m.getParentId()){
                objects.add(m);
            }else {
                Menu menu = collect.get(m.getParentId());
                if (null != menu){
                 menu.getChildren().add(m);
                }
            }
        }
        // 在遍历除去上级部门的集合，和全部的集合，如果parentId等于上级部门集合id,那么就存到对象的最后一个对象中
        return objects;
    }
}
